<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>


<form action=search_top.php method="GET">
	表格名稱 <input type="text" name="tbl" placeholder="liu_fu_cun"><BR>
	關鍵字 <input type="text" name="keyword" placeholder="六福村"><BR>
	英文名稱 <Input type="text" name=ename placeholder="LiuFuCun Park"><BR>
	中文名稱 <Input type="text" name=cname placeholder="六福村遊樂園"><BR>
	緯度<Input type="text" name=lat placeholder="24.825231"><BR>
	經度 <Input type="text" name=lon placeholder="121.180637"><BR>
	距離 <input type="text" name=distance value=1000><BR>
	國碼 <input type="text" name=iso placeholder="tw"><BR>
	<input type="submit" value="產生">

</form>
<?php
require("check_login.php");
require '../fb-library/src/facebook.php';
require 'config_root.php';
require 'db_api.php';

function distVincenty($lat1, $long1, $lat2, $long2) {
    $a = 6378137;
    $b = 6356752.314245;
    $f = 1/298.257223563;
    $L = deg2rad($long2 - $long1);
    $U1 = atan((1 - $f) * tan(deg2rad($lat1)));
    $U2 = atan((1 - $f) * tan(deg2rad($lat2)));
    $sinU1 = sin($U1);
    $cosU1 = cos($U1);
    $sinU2 = sin($U2);
    $cosU2 = cos($U2);
    $lambda = $L;
    $iterLimit = 100;
    do {
        $sinLambda = sin($lambda);
        $cosLambda = cos($lambda);
        $sinSigma = sqrt(($cosU2 * $sinLambda) * ($cosU2 * $sinLambda) + ($cosU1 * $sinU2 - $sinU1 * $cosU2 * $cosLambda) * ($cosU1 * $sinU2 - $sinU1 * $cosU2 * $cosLambda));
        if( $sinSigma == 0 ) {
            return 0;
        }
        $cosSigma = $sinU1 * $sinU2 + $cosU1 * $cosU2 * $cosLambda;
        $sigma = atan2($sinSigma, $cosSigma);
        $sinAlpha = $cosU1 * $cosU2 * $sinLambda / $sinSigma;
        $cosSqAlpha = 1 - $sinAlpha * $sinAlpha;
        if( $cosSqAlpha == 0 ) {
            $cos2SigmaM = 0;
        } else {
            $cos2SigmaM = $cosSigma - 2 * $sinU1 * $sinU2 / $cosSqAlpha;
        }
        $C = $f / 16 * $cosSqAlpha * (4 + $f * (4 - 3 * $cosSqAlpha));
        $lambdaP = $lambda;
        $lambda = $L + (1 - $C) * $f * $sinAlpha * ($sigma + $C * $sinSigma * ($cos2SigmaM + $C * $cosSigma * (-1 + 2 * $cos2SigmaM * $cos2SigmaM)));
    } while(abs($lambda - $lambdaP) > 0.000000000001 && --$iterLimit > 0);
    if( $iterLimit == 0 ) {
        return 0;
    }
    $uSq = $cosSqAlpha * ($a * $a - $b * $b) / ($b * $b);
    $A = 1 + $uSq / 16384 * (4096 + $uSq * (-768 + $uSq * (320 - 175 * $uSq)));
    $B = $uSq / 1024 * (256 + $uSq * (-128 + $uSq * (74 - 47 * $uSq)));
    $deltaSigma = $B * $sinSigma * ($cos2SigmaM + $B / 4 * ($cosSigma * (-1 + 2 * $cos2SigmaM * $cos2SigmaM) - $B / 6 * $cos2SigmaM * (-3 + 4 * $sinSigma * $sinSigma) * (-3 + 4 * $cos2SigmaM * $cos2SigmaM)));
    return $b * $A * ($sigma - $deltaSigma);
}

$config=array();
$config['appId']='607470316008019';	
$config['secret']='07ee2e52439a998afc5c41aaff2baa71';	
$config['cookie']=true;	

function comp($a,$b) {
	return $a['checkins'] < $b['checkins'];
}

if(!isset($_GET['tbl'])) die("表格名稱不能為空<BR>");
if(!isset($_GET['keyword'])) die("關鍵字不能為空<BR>");
if(!isset($_GET['ename'])) die("英文名不能為空<BR>");
if(!isset($_GET['cname'])) die("中文名稱不能為空<BR>");
if(!isset($_GET['lat'])) die("緯度不能為空<BR>");
if(!isset($_GET['lon'])) die("經度不能為空<BR>");
if(!isset($_GET['distance'])) die("距離不能為空<BR>");
if(!isset($_GET['iso'])) die("國碼不能為空<BR>");

$tbl       =trim($_GET['tbl']);
$keyword   =trim($_GET['keyword']);
$ename     =trim($_GET['ename']);
$cname     =trim($_GET['cname']);
$lat       =trim($_GET['lat']);
$lon       =trim($_GET['lon']);
$distance  =trim($_GET['distance']);
$iso       =trim($_GET['iso']);

echo "<H1> $tbl $ename $cname </H1><BR>";
$keyword = str_replace(" ", "%20", $keyword); 

$queryStringPlace="search?q=$keyword&type=place&center=$lat,$lon&distance=$distance";
$queryStringPage="search?q=$keyword&type=page&center=$lat,$lon&distance=$distance";



/***************************************/


$facebook = new Facebook($config);

$totalCheckIns = 0;
$pages = $facebook->api($queryStringPage);

if(isset($pages['data'])) {
	$pageCnt = count($pages['data']);
	echo "<H1>Total Pages =".count($pages['data'])."</H1><BR>";
	for($i=0;$i<$pageCnt;$i++ ) {
		$id = $pages['data'][$i]['id'];
		$pagename = $pages['data'][$i]['name'];
		$page = $facebook->api("/$id");
		if(isset($page['checkins']) ) {
			if(!isset($page['location']['latitude']))
				continue;
			 $plat = $page['location']['latitude'];
			 $plon = $page['location']['longitude'];
			 if(distVincenty($lat,$lon,$plat,$plon) > $distance)
				continue;
			 $checkins = $page['checkins'];
			 $totalCheckIns += $checkins;
			 $page_array[$i] = array (
				'name' => $pagename,
				'id' => $id,
				'checkins' => $checkins,
			);
		}
		
	} 
}
$places = $facebook->api($queryStringPlace);
if(isset($places['data'])) {
	$pageCnt = count($places['data']);
	echo "<H1>Total Places =".count($places['data'])."</H1><BR>";
	for($i=0;$i<$pageCnt;$i++ ) {
		$id = $places['data'][$i]['id'];
		$pagename = $places['data'][$i]['name'];
		$page = $facebook->api("/$id");
		if(isset($page['checkins']) ) {
			 $checkins = $page['checkins'];
			 $totalCheckIns += $checkins;
			 $place_array[$i] = array (
				'name' => $pagename,
				'id' => $id,
				'checkins' => $checkins,
			);
		}
		
	} 
}

$combined_array = array_merge($page_array,$place_array);
if(count($combined_array) > 0)
{

	uasort($combined_array, 'comp');
	$combined_array= array_values($combined_array);
	uasort($combined_array, 'comp');
	#要排2次才
	$t = count($combined_array);
	$totalCheckIns = $combined_array[0]['checkins'];
	for($i=1;$i<$t;$i++) {
		if($combined_array[$i]['id'] == $combined_array[$i-1]['id'])
			$combined_array[$i]['checkins'] = 0;
		$totalCheckIns += $combined_array[$i]['checkins'];
	}
	uasort($combined_array, 'comp');
	$combined_array= array_values($combined_array);
	uasort($combined_array, 'comp');

	echo "<BR><BR>";
	#for($i=0;$i<count($page_array);$i++) {
	#	$name=$page_array[$i]['name'];
	#	$id=$page_array[$i]['id'];
	#	$checkins = $page_array[$i]['checkins'];
	#	echo "Name:$name id:$id checkins:$checkins<BR>";
	#	$totalCheckIns += $checkins;
	#}
	$CheckinsSum = 0;
	$selectedRange=count($combined_array)-1;
	for($i=0;($i<count($combined_array) && ($i < 20));$i++) {
		$CheckinsSum += $combined_array[$i]['checkins'];
		$selectedRange=$i;
		$ratio = ($CheckinsSum / $totalCheckIns) ;
		if($ratio > 0.7) {
			break;
		}
		
	}
	echo "Select from 0 to $i, $ratio  <BR>";
	for($i=0;$i<=$selectedRange;$i++) {
		$saveArray[$i] = array(
			'name' => $combined_array[$i]['name'],
			'id' => $combined_array[$i]['id'],
			'checkins' => $combined_array[$i]['checkins'],
			'ratio' => $combined_array[$i]['checkins'] / $totalCheckIns,
		);
		echo  $combined_array[$i]['name'].", ".$combined_array[$i]['id'].
			 ", ".$combined_array[$i]['checkins'].
			 ", ". $combined_array[$i]['checkins'] / $totalCheckIns."<BR>";
	}
	#file_put_contents("data/$qjson".".txt",json_encode($saveArray));

	#touch("db_scene.json");
	#$db_scene=json_decode(file_get_contents("db_scene.json"), true);
	#$db_scene[$qjson] = array (
	#	'cname' => "$qname",
	#	'lat' => "$qlat",
	#	'lon' => "$qllat",
	#	'dist' => "$qdist",
	#);
	#file_put_contents("db_scene.json", json_encode($db_scene));
	
	
	addScene($tbl, $keyword, $ename, $cname, $distance, $lat, $lon, $iso);
	create_tbl_record($tbl);
	foreach($saveArray as $key => $value) {
		insert_tbl_sample(
			$tbl, 
			$value['id'], 
			$value['checkins'],
			$value['name'],
			$value['ratio']
		);
	}
}  
else {
	echo "<H1> No Match </H1>";
}
	
?>






